﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace EasyDDD.AdminModule.Host.WebAPI.ActionFilter
{
    public class PureAdminResponeActionFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var pure = new PureAdminRespones()
                {
                    Success = false,
                    Errors = context.ModelState.SelectMany(e => e.Value!.Errors)
                };
                context.Result = new ObjectResult(pure) { StatusCode = 500 };
            };

            //if (!context.HttpContext.Request.Path.StartsWithSegments("/api/AdminModule/"))
            //{
            //    return;
            //}
            //if (context.Result == null)
            //{
            //    return;
            //}
            //ObjectResult? result = context.Result as ObjectResult;
            //if (result == null)
            //{
            //    return;
            //}
            //var pure = new PureAdminRespones()
            //{
            //    Success = true,
            //    Data = result.Value
            //};
            //context.Result = new ObjectResult(pure);
        }


        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null && context.Result != null)
            {
                ObjectResult? result = context.Result as ObjectResult;
                if (result == null)
                {
                    return;
                }
                var pure = new PureAdminRespones()
                {
                    Success = true,
                    Data = result.Value
                };
                context.Result = new ObjectResult(pure);
            }
            //base.OnActionExecuted(context);
        }
    }

    public class PureAdminRespones
    {
        public bool Success { get; set; }

        public object? Data { get; set; } = default!;
        public object? Errors { get; set; } = default!;
    }
}

